﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Threading;
using System.Text;
using System.Net;
using UnityEngine;


public enum AppState
{
    ArtistsList,
    ImagesList
};


public class AppController: MonoBehaviour
{

    public String artscrollBaseHost = "http://www.artscroll.ru";
    public String artscrollPageAlias = "/page.php?al=";
    public String artscrollPageID = "/page.php?id=";

    public Dictionary<char, OrderedDictionary> artistsListRaw = new Dictionary<char, OrderedDictionary>();
    public Dictionary<Char, List<String>> artistsList = new Dictionary<Char, List<String>>();

    public UIPanel imagesPanel;
    public UIPanel artistsPanel;
    public UIPanel alphabetPanel;

    public ArtistDownloader artistsDownloader;
    public ImageGridController imagesGridController;
    public ArtistGridController artistGridController;

    public TextAsset textAsset;

    public IEnumerator downloadEnumetator;
    public IEnumerator doNothing;
    public IEnumerator currentTask;

    public GameObject recycleBin;
    public String selectedArtist;
    public Char selectedChar = 'A';

    public bool artistsListIsLoaded = false;
    public AppState appState = AppState.ArtistsList;

    WWW www;

    void Start () 
	{
        InitArtistsList();

        //RefreshArtistsGrid("a");

        currentTask = DoNothing();
        StartCoroutine(Work());
	}

    /*
     * Основной бесконечный цикл программы
     *
     * */
    IEnumerator Work()
    {
        while (true)
        {
            if (currentTask != null && currentTask.MoveNext())
                yield return currentTask.Current;
            else
                yield return null;

        }
    }
   
    public void ChangeTask(bool download, String artistName)
    {
        if (download)
            currentTask = ChangeArtist(artistName);
        else
            currentTask = DoNothing();
    }

    void InitArtistsList()
    {
        ArtistInfo artistInfo = new ArtistInfo();

        String s = textAsset.text;
        var split = s.Split('\n');
        Debug.Log(split.Length);
        foreach (string ss in split)
        {
            artistInfo = new ArtistInfo(ss);
            Debug.Log(artistInfo.artistName);
            if (!artistsListRaw.ContainsKey(artistInfo.artistName.ToUpper()[0]))
            {
                artistsListRaw.Add(artistInfo.artistName.ToUpper()[0], new OrderedDictionary());
                artistsList.Add(artistInfo.artistName.ToUpper()[0], new List<String>());
            }

            if (artistsListRaw[artistInfo.artistName.ToUpper()[0]][artistInfo.artistName] != null)
                continue;
            artistsListRaw[artistInfo.artistName.ToUpper()[0]].Add(artistInfo.artistName, artistInfo);
            artistsList[artistInfo.artistName.ToUpper()[0]].Add(artistInfo.artistName);
        }
        artistsListIsLoaded = true;
    }

    List<Texture2D> list = new List<Texture2D>();
    public IEnumerator ChangeArtist(String artistName)
    {
        Debug.Log("Change artist begin");
        //if(selectedArtist != null)
        //    (artistsListRaw[selectedChar][selectedArtist] as ArtistInfo).images = null;
        //for(int i = 0; i < (artistsListRaw[selectedChar][selectedArtist] as ArtistInfo).images.Count; i++)

        
        selectedArtist = artistName;
        ArtistInfo artistInfo = artistsListRaw[artistName[0]][artistName] as ArtistInfo;

        if (artistInfo.linkToImagesCache == false)
        {
            artistsDownloader.artistInfo = artistInfo;
            artistsDownloader.GetLinksToImages();
        }
        (artistsListRaw[artistName[0]][artistName] as ArtistInfo).imagesDone = new List<bool>((artistsListRaw[artistName[0]][artistName] as ArtistInfo).linksToImages.Count);
        for (int i = 0; i < (artistsListRaw[artistName[0]][artistName] as ArtistInfo).linksToImages.Count; i++)
            (artistsListRaw[artistName[0]][artistName] as ArtistInfo).imagesDone.Add(false);

        if ((artistInfo.linksToImages.Count != 0) && (artistInfo.images.Count < artistInfo.linksToImages.Count))
            {
                for (int i = 0; i < artistInfo.linksToImages.Count; i++)
                {
                    /*Кеширование изображений
                    if (artistsListRaw[artistName].imagesCache[i] == true)
                    {
                        Debug.Log("Add cached images to grid");
                        imagesGridController.AddCell(artistsListRaw[artistsListRaw[artistName].artistName], i);
                        continue;
                    }
                     * */

                    www = new WWW(artistInfo.linksToImages[i]);
                    while (true)
                    {
                        
                        yield return www;

                        if (www.isDone)
                        {
                            ImageInfo imageInfo = new ImageInfo(artistName, www.bytes, www.texture.height, www.texture.width, www.texture.format);
                            Debug.Log(GC.GetTotalMemory(false) / 1024);
                            (artistsListRaw[artistName[0]][artistName] as ArtistInfo).images.Add(imageInfo);
                            (artistsListRaw[artistName[0]][artistName] as ArtistInfo).imagesDone[i] = true;
                            Debug.Log(GC.GetTotalMemory(false) / 1024);
                            Debug.Log(www.size / 1024 );
                            GameObject.Destroy(www.texture);
                            Resources.UnloadUnusedAssets();
                            www = null;
                            imagesGridController.posChanged = true;
                            appState = AppState.ImagesList;
                            break;
                        }
                    }
                }
            }
            
            
    }


    IEnumerator DoNothing()
    {
        Debug.Log("Nothing()");
        while (true)
        {
            yield return null;
        }
    }


    /*
 * Обновить список художников, используя первую букву имени
 * 
 * */
    public void RefreshArtistsGrid(String firstChar)
    {
        Debug.Log("Start RefreshArtistsList()");
        //ClearArtistGrid();

        /*
        artistsPanel.GetComponent<UIPanel>().transform.localPosition = new Vector3(0f, 0f, 0f);
        Vector4 v4 = artistsPanel.GetComponent<UIPanel>().clipRange;
        v4.y -= v4.y;
        artistsPanel.GetComponent<UIPanel>().clipRange = v4;
        */
        
        /*
        for(int i = 0; i < artistsListRaw[firstChar[0]].Count; i++)
            artistGridController.AddCell((artistsListRaw[firstChar[0]][i] as ArtistInfo).artistName); 
        */    
        Debug.Log("RefreshArtistsList() is complete");
    }
    public void ShowImagesGrid(String artistName)
    {
        //ClearImageGrid();

        artistsPanel.enabled = false;
        artistsPanel.gameObject.SetActive(false);
        alphabetPanel.gameObject.SetActive(false);
        imagesPanel.enabled = true;

        imagesGridController.rightButton.enabled = true;
        imagesGridController.leftButton.enabled = true;


        ChangeTask(true, artistName);
    }
    public void ShowArtistsGrid()
    {
        artistsPanel.enabled = true;
        artistsPanel.gameObject.SetActive(true);
        alphabetPanel.gameObject.SetActive(true);
        imagesPanel.enabled = false;
        appState = AppState.ArtistsList;

        imagesGridController.rightButton.enabled = false;
        imagesGridController.leftButton.enabled = false;

        //ClearImageGrid();
        ChangeTask(false, "");
    }
        
    void ClearImageGrid()
    {
        imagesGridController.RemoveAllCells();
    }
    void ClearArtistGrid()
    {
        artistGridController.RemoveAllCells();
    }

}
